﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：吕海乐 
    //
    // 文件名：PurchaseGoodsList.cs
    // 文件功能描述：采购目录维护,有效采购目录，可以撤废采购目录
    // 创建标识：吕海乐2009-05-14
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using System.Data;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Hospitals.Procurement
{
    public partial class PurchaseGoodsList : BasePage
    {
        public PurchaseGoodsList()
        {
            this.ModuleNo = Module.产品库管理.ToString();
        }

        IBLL_ProcurementBasic ipb = Factory.BLL_ProcurementBasic();
        IBLL_HospitalProcureCatalog ihp = Factory.BLL_HospitalProcureCatalog();
        IBLL_Distribution id = Factory.BLL_Distribution();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HZ.DrugTrade.Web.Function.IsThreeLevel())//项目查询条件仅三级医院可见
            {
                this.ddlProjectid.Visible = false;
                this.lblProjectid.Visible = false;
            }
            if (!IsPostBack)
            {
                SetConditionFromCookie();

                setBind();
            }
        }

        #region cookie 查询条件相关

        /// <summary>
        /// 
        /// </summary>
        protected void SaveConditionIntoCookie()
        {
            if (IsPostBack)
            {
                setCookie("PurchaseGoodsList_txtOutLook", this.txtOutLook.Text);
                //setCookie("PurchaseGoodsList_txtPinyinCode", this.txtPinyinCode.Text);

                setCookie("PurchaseGoodsList_txtMaterial", this.txtMaterial.Text);
                setCookie("PurchaseGoodsList_txtUnit", this.txtUnit.Text);
                setCookie("PurchaseGoodsList_txtProduceCompany_SC", this.txtProduceCompany_SC.Text);
                //setCookie("PurchaseGoodsList_txtCompany_TB", this.txtCompany_TB.Text);

                setCookie("PurchaseGoodsList_txtCompany_PS", this.txtCompany_PS.Text);
                setCookie("PurchaseGoodsList_txtGoodsName", this.txtGoodsName.Text);
                //setCookie("PurchaseGoodsList_txtProductType", this.txtProductType.Text);

                setCookie("PurchaseGoodsList_CurrentlyPageIndex", AspNetPager1.CurrentPageIndex.ToString());
                setCookie("PurchaseGoodsList_CommandArgument", this.lbnSwitch.CommandArgument);
                //setCookie("PurchaseGoodsList_SortSource", this.ucSource1.SelectValue.ToString());
                //setCookie("PurchaseGoodsList_IsBasicRemedy", this.ucIsBasicRemedy1.SelectValue.ToString());
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="strValue"></param>
        protected void setCookie(string strName, string strValue)
        {
            HttpCookie cookie = new HttpCookie(strName);
            cookie.Value = HttpUtility.UrlEncode(strValue);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 
        /// </summary>
        protected void SetConditionFromCookie()
        {
            if (!IsPostBack)
            {
                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtOutLook"] != null)
                    this.txtOutLook.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtOutLook"].Value);
                //if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtPinyinCode"] != null)
                //    this.txtPinyinCode.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtPinyinCode"].Value);

                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtMaterial"] != null)
                    this.txtMaterial.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtMaterial"].Value);
                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtUnit"] != null)
                    this.txtUnit.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtUnit"].Value);
                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtProduceCompany_SC"] != null)
                    this.txtProduceCompany_SC.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtProduceCompany_SC"].Value);
                //if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtCompany_TB"] != null)
                //    this.txtCompany_TB.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtCompany_TB"].Value);

                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtCompany_PS"] != null)
                    this.txtCompany_PS.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtCompany_PS"].Value);
                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtGoodsName"] != null)
                    this.txtGoodsName.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtGoodsName"].Value);
                //if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtProductType"] != null)
                //    this.txtProductType.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_txtProductType"].Value);


                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_CurrentlyPageIndex"] != null)
                    AspNetPager1.CurrentPageIndex = int.Parse(HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_CurrentlyPageIndex"].Value) ?? "1");

                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_CommandArgument"] != null)
                    this.lbnSwitch.CommandArgument = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_CommandArgument"].Value);

                //add by hw 2010-04-20 高级查询中加入按‘产品属性’查询的条件
                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_SortSource"] != null)
                    this.lbnSwitch.CommandArgument = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_SortSource"].Value);

                if (HttpContext.Current.Request.Cookies["PurchaseGoodsList_IsBasicRemedy"] != null)
                    this.lbnSwitch.CommandArgument = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["PurchaseGoodsList_IsBasicRemedy"].Value);

                lbnSwitch_Click(new object(), EventArgs.Empty);

            }
        }
        #endregion
        /// <summary>
        /// 绑定医疗机构自身的采购目录
        /// </summary>
        private void setBind()
        {


            SaveConditionIntoCookie();

            //绑定所有医疗机构采购目录
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            Model.Query.HospitalProcureCatalog qHospitalCatalog = GetCondition();
            IList<Model.View.HospitalProcureCatalog> hosiptalCatalogList = ihp.GetHospitalProcureCatalog(qHospitalCatalog, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;

            gvwProduceCatalog.PageSize = AspNetPager1.PageSize;
            gvwProduceCatalog.DataSource = hosiptalCatalogList;
            gvwProduceCatalog.DataBind();
        }

        /// <summary>
        /// 获取查询条件
        /// </summary>
        /// <returns></returns>
        private Model.Query.HospitalProcureCatalog GetCondition()
        {
            Model.Query.HospitalProcureCatalog procureCatalog = new HZ.DrugTrade.Model.Query.HospitalProcureCatalog();
            procureCatalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            procureCatalog.GoodsID = txtGoodsid.Text.Trim();
            //procureCatalog.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                procureCatalog.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                procureCatalog.ProjectID = "0001";
            }
            procureCatalog.Companyname_Sc = txtProduceCompany_SC.Text.Trim();
            //procureCatalog.Companyname_Tb = txtCompany_TB.Text.Trim();
            procureCatalog.Companyname_Ps = txtCompany_PS.Text.Trim();
            procureCatalog.PinyinCode = this.txtpinyincode.Text.Trim();
            //procureCatalog.PinyinCode = this.txtPinyinCode.Text.Trim().ToUpper();
            procureCatalog.Outlookc = txtOutLook.Text.Trim();
            //procureCatalog.ProjectID = ddlProject.SelectedItem.Value;
            procureCatalog.Unit = txtUnit.Text.Trim();
            procureCatalog.GoodsName = txtGoodsName.Text.Trim();
            procureCatalog.Material = txtMaterial.Text.Trim();
            //string orgID = CurrentAccount.GetUser().Org.OrgID;
            //bool flag = ipb.GetIsJiCeng(orgID);//判断是否基层医疗机构 add by zdc
            //if (flag)//盟市添加的只能采购基本药物和内蒙基本药物 zdc
            //{
            //    procureCatalog.IsJiCeng = 0;
            //}
            //if (ucSource1.SelectValue != -1) procureCatalog.SortSource = ucSource1.SelectValue;
            //if (ucIsBasicRemedy1.SelectValue != -1) procureCatalog.IsBasicRemedy = ucIsBasicRemedy1.SelectValue;
            //procureCatalog.SortName = txtProductType.Text.Trim();
            procureCatalog.SortFields = " GoodsName asc ,Outlookc asc,ProcurecatalogID";

            procureCatalog.Hospital_IsUsing = true;
            procureCatalog.IsUsing = true;

            return procureCatalog;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            //setBind();
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            setBind();
        }

        /// <summary>
        /// 简单查询与高级查询间的转换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                txtMaterial.Text = "";
                //txtPinyinCode.Text = "";
                txtProduceCompany_SC.Text = "";
                txtUnit.Text = "";
                txtGoodsName.Text = "";
                txtCompany_PS.Text = "";
                //ddlProject.SelectedIndex = -1;
            }
        }

        /// <summary>
        /// 撤废所选的采购目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAbandon_Click(object sender, EventArgs e)
        {
            List<HospitalProcureCatalog> hospitalCatalogList = new List<HospitalProcureCatalog>();
            //获取所有选择的目录
            for (int i = 0; i < gvwProduceCatalog.Rows.Count; i++)
            {
                System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                if (chk.Checked == true)
                {
                    HospitalProcureCatalog catalog = new HospitalProcureCatalog();
                    catalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
                    catalog.ProcureCatalogID = Convert.ToString(gvwProduceCatalog.DataKeys[i].Value);
                    catalog.IsUsing = false;
                    hospitalCatalogList.Add(catalog);
                }
            }

            //调取方法，撤废所选的采购目录 
            if (ihp.InvalidateHospitalProcureCatalog_Batch(hospitalCatalogList) == 1)
            {
                setBind();
            }
            else
            {
                PageError("撤废失败！", this.ReturnUrl);
            }
        }

        //protected void gvwProduceCatalog_RowEditing(object sender, GridViewEditEventArgs e)
        //{
        //    gvwProduceCatalog.EditIndex = e.NewEditIndex;
        //    setBind();
        //}

        //protected void gvwProduceCatalog_RowUpdating(object sender, GridViewUpdateEventArgs e)
        //{

        //    HospitalProcureCatalog hospitalProcureCatalog = new HospitalProcureCatalog();
        //    hospitalProcureCatalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
        //    hospitalProcureCatalog.ProcureCatalogID = Convert.ToString(gvwProduceCatalog.DataKeys[e.RowIndex].Value);
        //    if (!string.IsNullOrEmpty(((TextBox)gvwProduceCatalog.Rows[e.RowIndex].FindControl("txtSellPrice")).Text.Trim()))
        //    {
        //        hospitalProcureCatalog.SellPrice = new HZ.Common.ConvertHelper(((TextBox)gvwProduceCatalog.Rows[e.RowIndex].FindControl("txtSellPrice")).Text.Trim()).ToDecimal;
        //    }
        //    else
        //    {
        //        HZ.Web.WebUtil.Alert("零售价不能为空！", this);
        //        ((TextBox)gvwProduceCatalog.Rows[e.RowIndex].FindControl("txtSellPrice")).Focus();
        //        return;
        //    }

        //    int result = ihp.UpdateHospitalProcureCatalogSellPrice(hospitalProcureCatalog);
        //    if (result == 1)
        //    {
        //        gvwProduceCatalog.EditIndex = e.RowIndex;
        //        setBind();
        //    }
        //    else
        //    {
        //        HZ.Web.WebUtil.Alert("更新失败！",this);
        //    }
        //}

        //protected void gvwProduceCatalog_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        //{
        //    gvwProduceCatalog.EditIndex = e.RowIndex;
        //    setBind();
        //}

        /// <summary>
        /// 设置零售价为修改状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEditSellPrice_Click(object sender, EventArgs e)
        {
            ViewState["EditStatus"] = "1";
            //设置按钮状态
            this.btnEditSellPrice.Visible = false;
            this.btnSaveSellPrice.Visible = true;

            setBind();
        }

        /// <summary>
        /// 绑定状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwProduceCatalog_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TextBox txtSellPrice = e.Row.FindControl("txtSellPrice") as TextBox;
                Label lblSellPrice = e.Row.FindControl("lblSellPrice") as Label;

                if (Convert.ToString(ViewState["EditStatus"]) == "1")
                {
                    txtSellPrice.Visible = true;
                    lblSellPrice.Visible = false;
                }
                else
                {
                    txtSellPrice.Visible = false;
                    lblSellPrice.Visible = true;
                }
            }
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    if (ddlProjectid.SelectedItem.Value == "0002")
                    {
                        e.Row.Cells[12].Text = "自主报价";
                    }
                    else
                    {
                        e.Row.Cells[12].Text = "采购限价";
                    }
                }
            }
        }

        /// <summary>
        /// 保存医疗机构零售价
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveSellPrice_Click(object sender, EventArgs e)
        {
            List<HospitalProcureCatalog> myList = new List<HospitalProcureCatalog>();
            for (int i = 0; i < gvwProduceCatalog.Rows.Count; i++)
            {
                System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                TextBox txtSellPrice = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtSellPrice");
                if (chk.Checked == true)
                {
                    //采购数量不能为“0”
                    if (txtSellPrice.Text.Trim() == "0")
                    {
                        HZ.Web.WebUtil.Alert("零售价不能为0！", this);
                        txtSellPrice.Focus();
                        return;
                    }

                    if (!string.IsNullOrEmpty(txtSellPrice.Text.Trim()) && HZ.Common.MyValidate.IsMoney(txtSellPrice.Text.Trim()))
                    {
                        HospitalProcureCatalog hospitalProcureCatalog = new HospitalProcureCatalog();
                        hospitalProcureCatalog.HospitalID = CurrentAccount.GetUser().Org.OrgID;
                        hospitalProcureCatalog.ProcureCatalogID = Convert.ToString(gvwProduceCatalog.DataKeys[i].Value);
                        hospitalProcureCatalog.SellPrice = new HZ.Common.ConvertHelper(txtSellPrice.Text.Trim()).ToDecimal;

                        myList.Add(hospitalProcureCatalog);
                    }
                    else
                    {
                        HZ.Web.WebUtil.Alert("采购数量或采购价格不能为空！", this);
                        txtSellPrice.Focus();
                        return;
                    }
                }
            }

            //循环保存
            foreach (HospitalProcureCatalog hospitalProcureCatalog in myList)
            {
                int result = ihp.UpdateHospitalProcureCatalogSellPrice(hospitalProcureCatalog);
                if (result != 1)
                {
                    HZ.Web.WebUtil.Alert("更新失败！", this);
                    return;
                }
            }

            ViewState["EditStatus"] = "0";
            //设置按钮状态
            this.btnEditSellPrice.Visible = true;
            this.btnSaveSellPrice.Visible = false;

            setBind();

        }
        /// <summary>
        /// 导出有效品种 2009-11-14
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Export_Click(object sender, EventArgs e)
        {
            Model.Query.HospitalProcureCatalog procureCatalog = GetCondition();
            //int totalcount = 0;
            //IList<Model.View.HospitalProcureCatalog> distributionList = ihp.GetHospitalProcureCatalog(procureCatalog, 1, 0, out totalcount);
            //DataTable dt = HZ.Data.ModelConvert.GetDataTableFromModel(distributionList);
            //HZ.Excel.ExcelHelper.ExportDataForWeb(dt, gvwProduceCatalog);
            string where = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition<HZ.DrugTrade.Model.Query.HospitalProcureCatalog>(procureCatalog, true);
            string sql = "";
            if (this.ddlProjectid.Visible != false)
            {
                sql = string.Format(@"SELECT '‘'||Goodsid 产品编号,sortname 目录名称,GoodsName 产品名称,Outlookc 规格型号,Material 材质,Count 最小包装数量,Unit 最小计量单位,CompanyName_SC_TB 生产企业代理,QualityLevel 产品类别,ProcurePrice 自主报价,Price 采购价,ProjectName 项目,CompanyName_PS 配送企业 FROM View_HospitalProcureCatalog  WHERE 1=1 {0}", where);
            }
            else
            {
                sql = string.Format(@"SELECT Goodsid 产品编号,sortname 目录名称,GoodsName 产品名称,Outlookc 规格型号,Material 材质,Count 最小包装数量,Unit 最小计量单位,CompanyName_SC_TB 生产企业代理,QualityLevel 产品类别,ProcurePrice 采购限价,Price 采购价,ProjectName 项目,CompanyName_PS 配送企业 FROM View_HospitalProcureCatalog  WHERE 1=1 {0}", where);
            }
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "有效采购目录.xls");
        }
    }
}
